<?php

class Application_Model_Categories extends Common_Model {

    public $tableName = 'Categories';
    private $params = array(
        'id' => null,
    );

    const T_DEFAULT = 0;
    const T_MENU = 1;

    public static $typ = array(
        self::T_DEFAULT => 'domyślny',
        self::T_MENU => 'element menu',
    );

    /**
     * 
     * @return \Zend_Paginator_Adapter_DbSelect
     */
    public function getAdapterPagin($where = null, $order = null) {

        $select = $this->db->select()->from('v_categories');

        if ($where != null)
            $select->where($where);
        if ($order != null)
            $select->order($order);
        $adapter = new Zend_Paginator_Adapter_DbSelect($select);

        return $adapter;
    }

    public function getToHome($parent, $col = null) {

        $cat = array();
        $pr = $this->getParent($parent);
        $p = null;
        $i = 0;
        $max = 15;
        while (($p = $this->getParent($parent)) != null && $i <= $max) {

            $parent = $p->parentId;
            $cat[] = $col!= null ? $p->{$col} :$p->toArray();
            $i+=1;
        }

        return $cat;
    }

    private function getParent($parent) {
        return $this->table->fetchRow('id=' . $parent);
    }

    public function getForm($params) {

        $params = array_merge($this->params, $params);

        $form = parent::getForm();

        $title = new Zend_Form_Element_Text('title', array(
                    'label' => 'Tytuł'
                ));
        $url = new Zend_Form_Element_Text('url', array(
                    'label' => 'Url'
                ));

        $short = new Zend_Form_Element_Textarea('short', array(
                    'label' => 'Któtki opis',
                    'class' => 'tinymce', //'markItUp',
                    'treść' => 'Krótka treść'
                ));

        $parents = $this->getForOptions(isset($params['id']) ? 'c.id<>' . $params['id'] : null);

        $parentId = new Zend_Form_Element_Select('parentId', array());
        $parentId->setLabel('Rodzic:')
                ->addMultiOptions($parents)
                ->setSeparator('-');
        $parentId->setValue(0);

        $position = new Zend_Form_Element_Select('position', array());
        $position->setLabel('Kolejność:')
                ->addMultiOptions(array(
                    -6 => -6,
                    -5 => -5,
                    -4 => -4,
                    -3 => -3,
                    -2 => -2,
                    -1 => -1,
                    0 => 0,
                    1 => 1,
                    2 => 2,
                    3 => 3,
                    4 => 4,
                    5 => 5,
                    6 => 6,
                ))->setValue(0);

        $cmsurl = new Zend_Form_Element_Select('cmsurl', array());
        $cmsurl->setLabel('CMS Url:')
                ->addMultiOptions(array())->setRegisterInArrayValidator(false);

        $isHome = new Zend_Form_Element_Checkbox('isHome', array(
                    'label' => 'Strona główna',
                ));
        $isDefault = new Zend_Form_Element_Checkbox('isDefault', array(
                    'label' => 'Jest domyślny?',
                ));

        $typ = new Zend_Form_Element_Radio('typ', array());
        $typ->setLabel('Typ:')
                ->addMultiOptions(self::$typ)
                ->setSeparator('-');
        $typ->setValue(0);

        $submit = new Zend_Form_Element_Submit('submitAndStay', array(
                    'label' => 'Wyślij i zostań',
                    'class' => 'ui-button round-all fr link-button'
                ));

        $submit->setDecorators(array('ViewHelper'));
        $form->getDisplayGroup('gr-submit')->addElement($submit);

        $form->addDisplayGroup(array(
            $parentId, $typ, $isHome, $isDefault, $position, $url, $cmsurl, $title, $short
                ), 'gr-main');

        return $form;
    }
    
    public function getMainForContent($contentId){
        
        $model = new Application_Model_ContentCategory();
        return $model->table->fetchRow('contentId='.$contentId.' and isMain=1');
        
    }

    public function getForOptions($where = null, $order = null, $addMain = true) {

        $select = $this->db
                ->select()
                ->from(array('c' => 'categories'), array('c.*'))
                ->joinLeft(array('ct' => 'content_category'), 'ct.categoryId=c.id', array('ct.contentId'))
        ;
        
        $select->order('parentId ASC');

        if ($where != null)
            $select->where($where);
        if ($order != null)
            $select->order($order);        
        
        //var_dump($select.'');exit();
        $result = $select->query();
        $tab = $result->fetchAll(Zend_Db::FETCH_ASSOC);
        
        $return = array();
        
        if($addMain)
            $return['0'] = '--Główna--';
        
        //var_dump($select . '');
        //exit();
        foreach ($tab as $item) {
            $return[$item['id']] = $item['title'];
        }

        return $return;
    }

    public function buildWhereFromFiltered($params) {
        $p = array();

        foreach ($params as $name => $param) {
            if ($param == -1)
                continue;
            switch ($name) {
                case "id";
                    $p[] = 'id = ' . $param . '';
                    break;
                case "title";
                    $p[] = 'title like "' . $param . '%"';
                    break;
                case "parentId";
                    $p[] = 'parentId=' . $param . '';
                    break;
            }
        }

        return count($p) > 0 ? '' . implode(' and ', $p) . '' : null;
    }

    public function buildOrderFromFiltered($params) {
        $p = array();

        foreach ($params as $name => $param) {
            if ($param == -1)
                continue;
            switch ($name) {
                case "id";
                    $p[] = 'id  ' . $param . '';
                    break;
                case "title";
                    $p[] = 'title  ' . $param . '';
                    break;
            }
        }

        return count($p) > 0 ? $p : null;
    }

    /**
     * 
     * @param array $options options to merge with opt in function
     * @return array
     */
    public function getCategories($options) {
        $opt = array();
        $opt = array_merge($opt, $options);

        $select = $this->db->select()->from('v_categories');

        if (isset($opt['where']) && !empty($opt['where']))
            $select->where($opt['where']);

        $select->order('position ASC');
        $result = $select->query(Zend_Db::FETCH_ASSOC);

        return $result ? $result->fetchAll() : array();
    }

}

